/*
 * MyTree.fx
 *
 * Created on 2009-7-14, 14:33:33
 */

package com.sjtu.fx.tools;

import javafx.ext.swing.*;
import javax.swing.*;
import javax.swing.tree.*;
import java.lang.Object;

public class MyTreeCell {

    public var text: String;
    public var cells: MyTreeCell[];
    public var value: Object;

    override function toString ():String {
        return text;
    }
}

public class MyTree extends SwingComponent{

    var tree: JTree;
    var model: DefaultTreeModel;

    public var selectedValue: java.lang.Object;

    public var action: function(obj:Object);


    public var root: MyTreeCell on replace{
        if (root != null){
            model.setRoot(getCell(root));

            var obj = model.getRoot();
            var tp = new TreePath(obj);
        }
    };


    override function createJComponent(): JComponent {
        tree = new JTree();
        model = tree.getModel() as DefaultTreeModel;

        var  mouseListener = java.awt.event.MouseAdapter {
            override function mousePressed(e: java.awt.event.MouseEvent) {
                var selRow = tree.getRowForLocation(e.getX(), e.getY());
                var selPath = tree.getPathForLocation(e.getX(), e.getY());
                var lastPath = selPath.getPathComponent(selPath.getPathCount() - 1);
                var obj = (lastPath as DefaultMutableTreeNode).getUserObject();

                if(action != null ){
                   action(obj);
                }

                if(selRow != - 1) {
                    if(e.getClickCount() == 1) {
                        selectedValue = obj;

                    }
                    else if(e.getClickCount() == 2) {
                    }
                }
                getJComponent().repaint();
            }
        };

        tree.addMouseListener(mouseListener);

        tree.setRootVisible(false);
        var scrollPane = new JScrollPane(tree);
        return scrollPane;

    }

    function getCell(cell: MyTreeCell): MutableTreeNode {
        var node = new DefaultMutableTreeNode(cell);
        for (c  in  cell.cells ){
            node.<<insert>>(getCell(c),node.getChildCount());
        }
        return node;
    }

}

